package com.lagou.xmls;



import com.lagou.io.Resource;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;


/**
 * @Description:解析sqlMapConfig.xml
 * @author liujunling
 * @date 2020/3/31
 */
public class XMLConfigBuilder {
    private final Configuration configuration = new Configuration();

    public Configuration parse(InputStream in) throws Exception {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(in);
        Element rootElement = document.getRootElement();

        //构建数据库对象
        List<Element> propertiesElement = rootElement.selectNodes("//properties");
        Properties properties = new Properties(4);
        for (Element element : propertiesElement) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.put(name,value);
        }
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);
        //解析mapper配置文件
        List<Element> mapperElement = rootElement.selectNodes("//mapper");

        for (Element element : mapperElement) {
            String resource = element.attributeValue("resource");
            XMLMappersBuilder xmlMapperBuilder = new XMLMappersBuilder(configuration);
            InputStream mapperConfigStream = Resource.getResourceAsStream(resource);
            xmlMapperBuilder.parse(mapperConfigStream);
        }
        return configuration;
    }
}
